# -*- coding:utf-8 -*-
"""
=============================
this is a feibot product,
all rights reserved.
www.feibot.com
@author: Gu Tianyuan
@email: g@feibot.com
@time: ${DATE}:${TIME}
@product: ${PRODUCT_NAME}
=============================
"""

import sys
from PyQt5.QtWidgets import QDialog, QApplication, QListView

import gtyTools.tools
from uiFiles import ui_networkSetting
import time
from gtyConfig import language
from gtyTools import tools, gtyTypes
import uiTools


class NetworkSetting(QDialog, ui_networkSetting.Ui_networkSetting):

    def __init__(self, mainPage, eventQ, parent=None):
        super(NetworkSetting, self).__init__(parent)
        self.setupUi(self)
        uiTools.centerAndSetIcon(self)
        self.eventQ = eventQ

        self.mainPage = mainPage
        # 配置的控制接口
        self.configHandlers = gtyTypes.ConfigHandlers()
        self.connectState = self.configHandlers.state.read("machine", "socketConnectState", "bool")

        # language
        # 处理不同的语言
        self.setWindowTitle('Network Setting')
        self.label.setText(language.networkSetting_ipAddress)
        self.btnSet.setText(language.networkSetting_set)
        self.btnBack.setText(language.networkSetting_back)
        if self.connectState:
            self.btnConnect.setText(language.networkSetting_connected)
        else:
            self.btnConnect.setText(language.networkSetting_disconnected)

        self.localPort = self.configHandlers.machine.read('socket', 'localPort')

        self.updateNetworkInfo()

        self.btnBack.clicked.connect(self.close)
        self.btnSet.clicked.connect(self.setTargetIp)
        self.btnConnect.clicked.connect(self.toggleConnect)
        self.comboBox.currentIndexChanged.connect(self.updateNetworkType)

        self.comboBox.addItems(['UDP', 'TCP Server'])
        self.comboBox.setStyleSheet("QAbstractItemView::item {height: 45px;}")
        self.comboBox.setView(QListView())
        if self.configHandlers.machine.read('socket', 'type').upper() == 'UDP':
            self.comboBox.setCurrentText('UDP')
        if self.configHandlers.machine.read('socket', 'type').upper() == 'TCP SERVER':
            self.comboBox.setCurrentText('TCP Server')
        self.mainPage.eventEngine.eventList["ui_socketConnectedResult"].connect(self.updateConnectBtn)
        self.updateNetworkType()

        self.setGeometry(-200, -200, self.width(), self.height())

        print(__file__,language.networkSetting_protocol)
        self.label_5.setText(language.networkSetting_protocol)

    def sendEvent(self, task, eventName, eventData=None):
        if eventData is None:
            eventData = []
        e = [eventName, eventData]
        try:
            if task.upper() in self.eventQ.keys():
                self.eventQ[task.upper()].put(e)
        except Exception as e:
            print(e)

    def updateNetworkInfo(self):
        networkInfo = tools.GetNetworkInfo()
        interface = ''
        ip = ''
        mask = ''
        gateWay = ''
        pleaseConnectFirst = False
        try:
            interface = networkInfo['Interface']
        except Exception as e:
            pleaseConnectFirst = True
        try:
            ip = networkInfo['IP']
        except Exception as e:
            pleaseConnectFirst = True
        try:
            mask = networkInfo['MASK']
        except Exception as e:
            pleaseConnectFirst = True
        try:
            gateWay = networkInfo['GATEWAYS']
        except Exception as e:
            pleaseConnectFirst = True
            if '172' in ip:
                print('1111111')
                pleaseConnectFirst = False
                gateWay = ''
        networkState = ''
        networkState += "interface: " + interface + ".   "
        networkState += "IP address: " + ip + ".\n"
        networkState += "local listening ip: " + self.localPort + '.   '
        networkState += "mask: " + mask + ". \n"
        networkState += "gate way: " + gateWay
        self.textEditInfo.setText(networkState)
        if pleaseConnectFirst:
            self.labelInfo.setText(language.networkSetting_connectInfo)
            self.labelInfo.setStyleSheet("color:rgb(200,0,0)")


    def setTargetIp(self):
        if self.comboBox.currentText() == 'UDP':
            ip = self.lineEditIp.text()
            port = self.lineEditPort.text()
            if gtyTools.tools.check_ip(ip) and 0 <= int(port) <= 65535:
                self.configHandlers.machine.write('socket', 'targetIp', ip)
                self.configHandlers.machine.write('socket', 'targetPort', port)
                self.configHandlers.machine.write('socket','type','udp')
                self.sendEvent('SOCKET', 'socket_loadConfigAndConnect', '')
                self.labelInfo.setText("Set ip and port ok!")
            else:
                self.labelInfo.setText("Set ip or port wrong!")
        if self.comboBox.currentText() == 'TCP Server':
            ip = self.lineEditIp.text()
            localPort = self.lineEditPort.text()
            if 0 <= int(localPort) <= 65535:
                self.configHandlers.machine.write('socket', 'targetIp', ip)
                self.configHandlers.machine.write('socket', 'localPort', localPort)
                self.configHandlers.machine.write('socket','type','TCP Server')
                self.sendEvent('SOCKET', 'socket_loadConfigAndConnect', '')
                self.labelInfo.setText("Set listening port ok!")

    # 更新socket连接的结果
    def updateConnectBtn(self, res):
        if res:
            print(__file__, 'connect: true')
            self.btnConnect.setText(language.networkSetting_connected)
        else:
            print(__file__, 'connect: false')
            self.btnConnect.setText(language.networkSetting_disconnected)
        self.connectState = res

    # 按下连接按钮
    def toggleConnect(self):
        if self.connectState:
            self.sendEvent('SOCKET', 'socket_disconnect', '')
        else:
            self.sendEvent('SOCKET', 'socket_connect', '')

    # 更新协议类型
    def updateNetworkType(self):
        if self.comboBox.currentText() == 'UDP':
            self.label_4.setText(language.networkSetting_udpTarget)
            self.label_2.setText(language.networkSetting_targetIp)
            self.label_3.setText(language.networkSetting_targetPort)
            self.lineEditIp.setText(self.configHandlers.machine.read('socket', 'targetIp'))
            self.lineEditPort.setText(self.configHandlers.machine.read('socket', 'targetPort'))
            self.lineEditIp.setReadOnly(False)

        if self.comboBox.currentText() == 'TCP Server':
            networkInfo = tools.GetNetworkInfo()
            self.label_4.setText('TCP Server settings')
            self.label_2.setText('local ip')
            self.label_3.setText('listening port')
            try:
                self.lineEditIp.setText(networkInfo['IP'])
            except:
                pass
            # self.lineEditIp.setReadOnly(True)
            self.lineEditPort.setText(self.configHandlers.machine.read('socket', 'localPort'))
